package state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.junit.Test;

public class Flink_State_wordcount {
    public static class MyStateFunc extends RichMapFunction<Tuple2<String, Integer>,Tuple2<String, Integer>>{
        //声明状态
        private ValueState<Integer> count;

        @Override
        public void open(Configuration parameters) throws Exception {
            //状态初始化
            count = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("key-count",Integer.class,0));
        }

        @Override
        public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
            //获取状态
            Integer lastCount = count.value();
            //更新状态
            count.update(lastCount+value.f1);

            return new Tuple2<>(value.f0,count.value());
        }
    }

    //TODO 使用状态编程实现wordcount
    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        env.readTextFile("input/1.txt")
                .flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        for (String s : value.split(" ")) {
                            out.collect(new Tuple2<>(s,1));
                        }
                    }
                })
                .keyBy(value -> value.f0)
                .map(new RichMapFunction<Tuple2<String, Integer>, Tuple2<String,Integer>>() {

                    private ValueState<Integer> sum;

                    @Override
                    public void open(Configuration configuration){
                        sum = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastSum",Integer.class));
                    }

                    @Override
                    public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
                        Integer temp = sum.value();
                        if(temp!=null){
                            sum.update(value.f1+temp);
                        }else{
                            sum.update(value.f1);
                        }
                        return new Tuple2<>(value.f0,sum.value());
                    }
                })
                .print();
        env.execute();
    }

}

